<?php

/*
 * [Discuz!] (C)2001-2007 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: global.func.php 10115 2007-08-24 00:58:08Z cnteacher $
 */

/**
 * 生成主键序列
 *
 * @return Ambigous <multitype:, unknown>
 */
function getCurrentId() {
	global $mysqlTools;
	
	try {
		$mysqlTools->startTransaction ();
		$result = $mysqlTools->executeSql ( "
				update sys_info set sys_sequence_id = sys_sequence_id+1
			" );
		$currentId = $mysqlTools->selectSql ( "
                select sys_sequence_id from sys_info where sys_id = 20131024
            " )[0]['sys_sequence_id'];
		$mysqlTools->commitTransaction ();
		return $currentId;
	} catch ( \Exception $e ) {
		$mysqlTools->rollback ();
	}
}

/**
 * 为二维数组做添加,删除,移动的操作并重新给指定数组的sort字段排序
 *
 * @param $targetAarray 目标排序数组        	
 * @param $operate 'add'
 *        	添加排序 or 'add' 删除排序 or 'move'已有元素移动到指定位置并重新排序,不传则只排序
 * @param $id 需要操作的元素唯一标识key,默认值'id'        	
 * @param $sort 需要排序的key,默认值'sort'        	
 * @param $operateArray array
 *        	<id,sort> 操作数组应为要操作的数组元素,id:需要操作的元素唯一标识,sort>=1 需要更新到的位置 sort<1则sort=1
 * @return array [<id, sort>] 排序好的数组
 *        
 */
function arraySort($targetAarray = array(), $id = 'id', $sort = 'sort', $operateArray = null, $operate = null) {
	if (empty ( $targetAarray ))
		return array ();
	if ($operateArray != null && $operateArray [$sort] < 1)
		$operateArray [$sort] = 1;
	for($i = 0; $i < count ( $targetAarray ); $i ++) {
		$targetAarray [$i] [$sort] = $i + 1; // 重置序列
	}
	switch ($operate) {
		case 'add' :
			if ($operateArray [$sort] > count ( $targetAarray ) + 1)
				$operateArray [$sort] = count ( $targetAarray ) + 1;
			for($i = 0; $i < count ( $targetAarray ); $i ++) {
				
				if ($i >= $operateArray [$sort] - 1) {
					$targetAarray [$i] [$sort] ++;
				}
			}
			array_splice ( $targetAarray, $operateArray [$sort] - 1, 0, array (
					$operateArray 
			) );
			break;
		case 'del' :
			$num = count ( $targetAarray );
			for($i = 0; $i < count ( $targetAarray ); $i ++) {
				
				if ($targetAarray [$i] [$id] == $operateArray [$id]) {
					array_splice ( $targetAarray, $i, 1 );
					$num = $i;
				}
				if ($i >= $num) {
					$targetAarray [$i] [$sort] --;
				}
			}
			break;
		case 'move' :
			if ($operateArray [$sort] > count ( $targetAarray ))
				$operateArray [$sort] = count ( $targetAarray );
			$original = 1;
			foreach ( $targetAarray as $key => $value ) {
				if ($value [$id] == $operateArray [$id]) {
					$original = $key;
				}
			}
			$m = $operateArray [$sort] > $original;
			for($i = ($m ? $original : $operateArray [$sort] - 1); $i < ($m ? $operateArray [$sort] : $original); $i ++) {
				$m ? $targetAarray [$i] [$sort] -- : $targetAarray [$i] [$sort] ++;
			}
			array_splice ( $targetAarray, $original, 1 );
			array_splice ( $targetAarray, $operateArray [$sort] - 1, 0, array (
					$operateArray 
			) );
			break;
		default :
			break;
	}
	return $targetAarray;
}

/**
 * 生成一个唯一的字符ID
 *
 * @return string
 */
function guid() {
	$charid = strtoupper ( md5 ( uniqid ( mt_rand (), true ) ) );
	
	$uuid = substr ( $charid, 0, 8 ) . substr ( $charid, 8, 4 ) . substr ( $charid, 12, 4 ) . substr ( $charid, 16, 4 ) . substr ( $charid, 20, 12 );
	
	return $uuid;
}

// 递归创建目录
function makeDir($path) {
	$path = str_replace ( array (
			'/',
			'\\',
			'//',
			'\\\\' 
	), DIRECTORY_SEPARATOR, $path );
	$path = str_replace ( SITE_PATH . '\\', '', $path ); // 替换网站根路径， ROOT_PATH 通常可以在配置文件里定义
	$dirs = explode ( DIRECTORY_SEPARATOR, $path );
	$relativePath = '';
	foreach ( $dirs as $dir ) {
		if ($dir) {
			$relativePath .= $dir . DIRECTORY_SEPARATOR;
			$realPath = SITE_PATH . '\\' . $relativePath;
			if (! file_exists ( $realPath ) && ! @mkdir ( $realPath, 0777 )) {
				return $realPath;
			}
		}
	}
	return true;
}

/**
 * XML编码
 *
 * @param mixed $data
 *        	数据
 * @param string $root
 *        	根节点名
 * @param string $item
 *        	数字索引的子节点名
 * @param string $attr
 *        	根节点属性
 * @param string $id
 *        	数字索引子节点key转换的属性名
 * @param string $encoding
 *        	数据编码
 * @return string
 */
function xml_encode($data, $root = 'think', $item = 'item', $attr = '', $id = 'id', $encoding = 'utf-8') {
	if (is_array ( $attr )) {
		$_attr = array ();
		foreach ( $attr as $key => $value ) {
			$_attr [] = "{$key}=\"{$value}\"";
		}
		$attr = implode ( ' ', $_attr );
	}
	$attr = trim ( $attr );
	$attr = empty ( $attr ) ? '' : " {$attr}";
	$xml = "<?xml version=\"1.0\" encoding=\"{$encoding}\"?>";
	$xml .= "<{$root}{$attr}>";
	$xml .= data_to_xml ( $data, $item, $id );
	$xml .= "</{$root}>";
	return $xml;
}

/**
 * 数据XML编码
 *
 * @param mixed $data
 *        	数据
 * @param string $item
 *        	数字索引时的节点名称
 * @param string $id
 *        	数字索引key转换为的属性名
 * @return string
 */
function data_to_xml($data, $item = 'item', $id = 'id') {
	$xml = $attr = '';
	foreach ( $data as $key => $val ) {
		if (is_numeric ( $key )) {
			$id && $attr = " {$id}=\"{$key}\"";
			$key = $item;
		}
		$xml .= "<{$key}{$attr}>";
		$xml .= (is_array ( $val ) || is_object ( $val )) ? data_to_xml ( $val, $item, $id ) : $val;
		$xml .= "</{$key}>";
	}
	return $xml;
}

/**
 * 异常信息记录
 *
 * @param string $logInfo        	
 */
function exceptionLog($logInfo) {
	$filename = $_SERVER ["DOCUMENT_ROOT"] . '/exceptionLog.txt';
	
	if (file_exists ( $filename )) {
		$content = file ( $filename );
		$content .= $logInfo;
		$fp = fopen ( $filename, "w" );
		fputs ( $fp, "$content" );
		fclose ( $fp );
	} else {
		$fh = fopen ( $filename, "w" );
		if ($fh == false)
			die ( "unable to create file" );
		fputs ( $fh, $logInfo );
		fclose ( $fh );
		$count = file ( $filename );
	}
}

/**
 * 生成验证码
 */
function authcode($string, $operation, $key = '') {
	$key = md5 ( $key ? $key : $GLOBALS ['discuz_auth_key'] );
	$key_length = strlen ( $key );
	
	$string = $operation == 'DECODE' ? base64_decode ( $string ) : substr ( md5 ( $string . $key ), 0, 8 ) . $string;
	$string_length = strlen ( $string );
	
	$rndkey = $box = array ();
	$result = '';
	
	for($i = 0; $i <= 255; $i ++) {
		$rndkey [$i] = ord ( $key [$i % $key_length] );
		$box [$i] = $i;
	}
	
	for($j = $i = 0; $i < 256; $i ++) {
		$j = ($j + $box [$i] + $rndkey [$i]) % 256;
		$tmp = $box [$i];
		$box [$i] = $box [$j];
		$box [$j] = $tmp;
	}
	
	for($a = $j = $i = 0; $i < $string_length; $i ++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box [$a]) % 256;
		$tmp = $box [$a];
		$box [$a] = $box [$j];
		$box [$j] = $tmp;
		$result .= chr ( ord ( $string [$i] ) ^ ($box [($box [$a] + $box [$j]) % 256]) );
	}
	
	if ($operation == 'DECODE') {
		if (substr ( $result, 0, 8 ) == substr ( md5 ( substr ( $result, 8 ) . $key ), 0, 8 )) {
			return substr ( $result, 8 );
		} else {
			return '';
		}
	} else {
		return str_replace ( '=', '', base64_encode ( $result ) );
	}
}
function clearcookies() {
	global $discuz_uid, $discuz_user, $discuz_pw, $discuz_secques, $adminid, $credits;
	dsetcookie ( 'sid', '', - 86400 * 365 );
	dsetcookie ( 'auth', '', - 86400 * 365 );
	dsetcookie ( 'visitedfid', '', - 86400 * 365 );
	dsetcookie ( 'onlinedetail', '', - 86400 * 365, 0 );
	
	$discuz_uid = $adminid = $credits = 0;
	$discuz_user = $discuz_pw = $discuz_secques = '';
}

/**
 * 字符串截断方法
 */
function cutstr($string, $length, $dot = ' ...') {
	global $charset;
	
	if (strlen ( $string ) <= $length) {
		return $string;
	}
	
	$string = str_replace ( array (
			'&amp;',
			'&quot;',
			'&lt;',
			'&gt;' 
	), array (
			'&',
			'"',
			'<',
			'>' 
	), $string );
	
	$strcut = '';
	if (strtolower ( $charset ) == 'utf-8') {
		
		$n = $tn = $noc = 0;
		while ( $n < strlen ( $string ) ) {
			
			$t = ord ( $string [$n] );
			if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1;
				$n ++;
				$noc ++;
			} elseif (194 <= $t && $t <= 223) {
				$tn = 2;
				$n += 2;
				$noc += 2;
			} elseif (224 <= $t && $t < 239) {
				$tn = 3;
				$n += 3;
				$noc += 2;
			} elseif (240 <= $t && $t <= 247) {
				$tn = 4;
				$n += 4;
				$noc += 2;
			} elseif (248 <= $t && $t <= 251) {
				$tn = 5;
				$n += 5;
				$noc += 2;
			} elseif ($t == 252 || $t == 253) {
				$tn = 6;
				$n += 6;
				$noc += 2;
			} else {
				$n ++;
			}
			
			if ($noc >= $length) {
				break;
			}
		}
		if ($noc > $length) {
			$n -= $tn;
		}
		
		$strcut = substr ( $string, 0, $n );
	} else {
		for($i = 0; $i < $length; $i ++) {
			$strcut .= ord ( $string [$i] ) > 127 ? $string [$i] . $string [++ $i] : $string [$i];
		}
	}
	
	$strcut = str_replace ( array (
			'&',
			'"',
			'<',
			'>' 
	), array (
			'&amp;',
			'&quot;',
			'&lt;',
			'&gt;' 
	), $strcut );
	
	return $strcut . $dot;
}
function daddslashes($string, $force = 0) {
	! defined ( 'MAGIC_QUOTES_GPC' ) && define ( 'MAGIC_QUOTES_GPC', get_magic_quotes_gpc () );
	
	if (! MAGIC_QUOTES_GPC || $force) {
		if (is_array ( $string )) {
			foreach ( $string as $key => $val ) {
				$string [$key] = daddslashes ( $val, $force );
			}
		} else {
			$string = addslashes ( $string );
		}
	}
	return $string;
}
function datecheck($ymd, $sep = '-') {
	if (! empty ( $ymd )) {
		list ( $year, $month, $day ) = explode ( $sep, $ymd );
		return checkdate ( $month, $day, $year );
	} else {
		return FALSE;
	}
}
function debuginfo() {
	if ($GLOBALS ['debug']) {
		global $db, $discuz_starttime, $debuginfo;
		$mtime = explode ( ' ', microtime () );
		$debuginfo = array (
				'time' => number_format ( ($mtime [1] + $mtime [0] - $discuz_starttime), 6 ),
				'queries' => $db->querynum 
		);
		return TRUE;
	} else {
		return FALSE;
	}
}
function dhtmlspecialchars($string) {
	if (is_array ( $string )) {
		foreach ( $string as $key => $val ) {
			$string [$key] = dhtmlspecialchars ( $val );
		}
	} else {
		$string = preg_replace ( '/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1', str_replace ( array (
				'&',
				'"',
				'<',
				'>' 
		), array (
				'&amp;',
				'&quot;',
				'&lt;',
				'&gt;' 
		), $string ) );
	}
	return $string;
}
function dheader($string, $replace = true, $http_response_code = 0) {
	$string = str_replace ( array (
			"\r",
			"\n" 
	), array (
			'',
			'' 
	), $string );
	if (empty ( $http_response_code ) || PHP_VERSION < '4.3') {
		@header ( $string, $replace );
	} else {
		@header ( $string, $replace, $http_response_code );
	}
	if (preg_match ( '/^\s*location:/is', $string )) {
		exit ();
	}
}
function disuploadedfile($file) {
	return function_exists ( 'is_uploaded_file' ) && (is_uploaded_file ( $file ) || is_uploaded_file ( str_replace ( '\\\\', '\\', $file ) ));
}
function dsetcookie($var, $value, $life = 0, $prefix = 1) {
	global $cookiepre, $cookiedomain, $cookiepath, $timestamp, $_SERVER;
	setcookie ( ($prefix ? $cookiepre : '') . $var, $value, $life ? $timestamp + $life : 0, $cookiepath, $cookiedomain, $_SERVER ['SERVER_PORT'] == 443 ? 1 : 0 );
}
function emailconv($email, $tolink = 1) {
	$email = str_replace ( array (
			'@',
			'.' 
	), array (
			'&#64;',
			'&#46;' 
	), $email );
	return $tolink ? '<a href="mailto: ' . $email . '">' . $email . '</a>' : $email;
}
function getrobot() {
	if (! defined ( 'IS_ROBOT' )) {
		$kw_spiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla';
		$kw_browsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla';
		if (preg_match ( "/($kw_browsers)/", $_SERVER ['HTTP_USER_AGENT'] )) {
			define ( 'IS_ROBOT', FALSE );
		} elseif (preg_match ( "/($kw_spiders)/", $_SERVER ['HTTP_USER_AGENT'] )) {
			define ( 'IS_ROBOT', TRUE );
		} else {
			define ( 'IS_ROBOT', FALSE );
		}
	}
	return IS_ROBOT;
}
function fileext($filename) {
	return trim ( substr ( strrchr ( $filename, '.' ), 1, 10 ) );
}
function formhash($specialadd = '') {
	global $discuz_user, $discuz_uid, $discuz_pw, $timestamp, $discuz_auth_key;
	$hashadd = defined ( 'IN_ADMINCP' ) ? 'Only For Discuz! Admin Control Panel' : '';
	return substr ( md5 ( substr ( $timestamp, 0, - 7 ) . $discuz_user . $discuz_uid . $discuz_pw . $discuz_auth_key . $hashadd . $specialadd ), 8, 8 );
}
function groupexpiry($terms) {
	$terms = is_array ( $terms ) ? $terms : unserialize ( $terms );
	$groupexpiry = isset ( $terms ['main'] ['time'] ) ? intval ( $terms ['main'] ['time'] ) : 0;
	if (is_array ( $terms ['ext'] )) {
		foreach ( $terms ['ext'] as $expiry ) {
			if ((! $groupexpiry && $expiry) || $expiry < $groupexpiry) {
				$groupexpiry = $expiry;
			}
		}
	}
	return $groupexpiry;
}
function ipaccess($ip, $accesslist) {
	return preg_match ( "/^(" . str_replace ( array (
			"\r\n",
			' ' 
	), array (
			'|',
			'' 
	), preg_quote ( $accesslist, '/' ) ) . ")/", $ip );
}
function language($file, $templateid = 0, $tpldir = '') {
	$tpldir = $tpldir ? $tpldir : TPLDIR;
	$templateid = $templateid ? $templateid : TEMPLATEID;
	
	$languagepack = DISCUZ_ROOT . './' . $tpldir . '/' . $file . '.lang.php';
	if (file_exists ( $languagepack )) {
		return $languagepack;
	} elseif ($templateid != 1 && $tpldir != './templates/default') {
		return language ( $file, 1, './templates/default' );
	} else {
		return FALSE;
	}
}
function multi($num, $perpage, $curpage, $mpurl, $maxpages = 0, $page = 10, $autogoto = TRUE, $simple = FALSE) {
	global $maxpage;
	$ajaxtarget = ! empty ( $_GET ['ajaxtarget'] ) ? " ajaxtarget=\"" . dhtmlspecialchars ( $_GET ['ajaxtarget'] ) . "\" " : '';
	
	$multipage = '';
	$mpurl .= strpos ( $mpurl, '?' ) ? '&amp;' : '?';
	$realpages = 1;
	if ($num > $perpage) {
		$offset = 2;
		
		$realpages = @ceil ( $num / $perpage );
		$pages = $maxpages && $maxpages < $realpages ? $maxpages : $realpages;
		
		if ($page > $pages) {
			$from = 1;
			$to = $pages;
		} else {
			$from = $curpage - $offset;
			$to = $from + $page - 1;
			if ($from < 1) {
				$to = $curpage + 1 - $from;
				$from = 1;
				if ($to - $from < $page) {
					$to = $page;
				}
			} elseif ($to > $pages) {
				$from = $pages - $page + 1;
				$to = $pages;
			}
		}
		
		$multipage = ($curpage - $offset > 1 && $pages > $page ? '<a href="' . $mpurl . 'page=1" class="first"' . $ajaxtarget . '>1 ...</a>' : '') . ($curpage > 1 && ! $simple ? '<a href="' . $mpurl . 'page=' . ($curpage - 1) . '" class="prev"' . $ajaxtarget . '>&lsaquo;&lsaquo;</a>' : '');
		for($i = $from; $i <= $to; $i ++) {
			$multipage .= $i == $curpage ? '<strong>' . $i . '</strong>' : '<a href="' . $mpurl . 'page=' . $i . ($ajaxtarget && $i == $pages && $autogoto ? '#' : '') . '"' . $ajaxtarget . '>' . $i . '</a>';
		}
		
		$multipage .= ($curpage < $pages && ! $simple ? '<a href="' . $mpurl . 'page=' . ($curpage + 1) . '" class="next"' . $ajaxtarget . '>&rsaquo;&rsaquo;</a>' : '') . ($to < $pages ? '<a href="' . $mpurl . 'page=' . $pages . '" class="last"' . $ajaxtarget . '>... ' . $realpages . '</a>' : '') . (! $simple && $pages > $page && ! $ajaxtarget ? '<kbd><input type="text" name="custompage" size="3" onkeydown="if(event.keyCode==13) {window.location=\'' . $mpurl . 'page=\'+this.value; return false;}" /></kbd>' : '');
		
		$multipage = $multipage ? '<div class="pages">' . (! $simple ? '<em>&nbsp;' . $num . '&nbsp;</em>' : '') . $multipage . '</div>' : '';
	}
	$maxpage = $realpages;
	return $multipage;
}
function rewrite_thread($tid, $page = 0, $prevpage = 0, $extra = '') {
	return '<a href="thread-' . $tid . '-' . ($page ? $page : 1) . '-' . ($prevpage && ! IS_ROBOT ? $prevpage : 1) . '.html"' . stripslashes ( $extra ) . '>';
}
function rewrite_forum($fid, $page = 0, $extra = '') {
	return '<a href="forum-' . $fid . '-' . ($page ? $page : 1) . '.html"' . stripslashes ( $extra ) . '>';
}
function rewrite_space($uid, $username, $extra = '') {
	$GLOBALS ['rewritecompatible'] && $username = rawurlencode ( $username );
	return '<a href="space-' . ($uid ? 'uid-' . $uid : 'username-' . $username) . '.html"' . stripslashes ( $extra ) . '>';
}
function rewrite_tag($name, $extra = '') {
	$GLOBALS ['rewritecompatible'] && $name = rawurlencode ( $name );
	return '<a href="tag-' . $name . '.html"' . stripslashes ( $extra ) . '>';
}
function quescrypt($questionid, $answer) {
	return $questionid > 0 && $answer != '' ? substr ( md5 ( $answer . md5 ( $questionid ) ), 16, 8 ) : '';
}
function random($length, $numeric = 0) {
	PHP_VERSION < '4.2.0' && mt_srand ( ( double ) microtime () * 1000000 );
	if ($numeric) {
		$hash = sprintf ( '%0' . $length . 'd', mt_rand ( 0, pow ( 10, $length ) - 1 ) );
	} else {
		$hash = '';
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
		$max = strlen ( $chars ) - 1;
		for($i = 0; $i < $length; $i ++) {
			$hash .= $chars [mt_rand ( 0, $max )];
		}
	}
	return $hash;
}
function removedir($dirname, $keepdir = FALSE) {
	$dirname = wipespecial ( $dirname );
	
	if (! is_dir ( $dirname )) {
		return FALSE;
	}
	$handle = opendir ( $dirname );
	while ( ($file = readdir ( $handle )) !== FALSE ) {
		if ($file != '.' && $file != '..') {
			$dir = $dirname . DIRECTORY_SEPARATOR . $file;
			is_dir ( $dir ) ? removedir ( $dir ) : unlink ( $dir );
		}
	}
	closedir ( $handle );
	return ! $keepdir ? (@rmdir ( $dirname ) ? TRUE : FALSE) : TRUE;
}
function sendmail($email_to, $email_subject, $email_message, $email_from = '') {
	extract ( $GLOBALS, EXTR_SKIP );
	require DISCUZ_ROOT . './include/sendmail.inc.php';
}
function showstars($num) {
	global $starthreshold;
	
	$alt = 'alt="Rank: ' . $num . '"';
	if (empty ( $starthreshold )) {
		for($i = 0; $i < $num; $i ++) {
			echo '<img src="' . IMGDIR . '/star_level1.gif" ' . $alt . ' />';
		}
	} else {
		for($i = 3; $i > 0; $i --) {
			$numlevel = intval ( $num / pow ( $starthreshold, ($i - 1) ) );
			$num = ($num % pow ( $starthreshold, ($i - 1) ));
			for($j = 0; $j < $numlevel; $j ++) {
				echo '<img src="' . IMGDIR . '/star_level' . $i . '.gif" ' . $alt . ' />';
			}
		}
	}
}
function site() {
	return $_SERVER ['HTTP_HOST'];
}
function strexists($haystack, $needle) {
	return ! (strpos ( $haystack, $needle ) === FALSE);
}
function implodeids($array) {
	if (! empty ( $array )) {
		return "'" . implode ( "','", is_array ( $array ) ? $array : array (
				$array 
		) ) . "'";
	} else {
		return '';
	}
}
function wipespecial($str) {
	return str_replace ( array (
			'..',
			"\n",
			"\r" 
	), array (
			'',
			'',
			'' 
	), $str );
}
function supe_dbconnect() {
	global $supe, $db;
	
	if (! $supe ['status']) {
		return FALSE;
	} elseif (empty ( $supe ['dbmode'] )) {
		$supe ['db'] = $db;
	} elseif (empty ( $supe ['db'] )) {
		$supe ['db'] = new dbstuff ();
		$supe ['link'] = $supe ['db']->connect ( $supe ['dbhost'], $supe ['dbuser'], $supe ['dbpw'], $supe ['dbname'], $supe ['pconnect'], FALSE );
		$supe ['status'] = $supe ['link'] ? $supe ['link'] : FALSE;
	}
}
function checkmd5($md5, $verified, $salt = '') {
	if (md5 ( $md5 . $salt ) == $verified) {
		$result = ! empty ( $salt ) ? 1 : 2;
	} elseif (empty ( $salt )) {
		$result = $md5 == $verified ? 3 : ((strlen ( $verified ) == 16 && substr ( $md5, 8, 16 ) == $verified) ? 4 : 0);
	} else {
		$result = 0;
	}
	return $result;
}
function dfopen($url, $limit = 500000, $post = '', $cookie = '', $bysocket = FALSE) {
	global $version, $boardurl;
	if (ini_get ( 'allow_url_fopen' ) && ! $bysocket && ! $post) {
		$fp = @fopen ( $url, 'r' );
		$s = @fread ( $fp, $limit );
		@fclose ( $fp );
		return $s;
	}
	$return = '';
	$matches = parse_url ( $url );
	$host = $matches ['host'];
	$script = $matches ['path'] . '?' . $matches ['query'] . '#' . $matches ['fragment'];
	$port = ! empty ( $matches ['port'] ) ? $matches ['port'] : 80;
	if ($post) {
		$out = "POST $script HTTP/1.1\r\n";
		$out .= "Accept: */*\r\n";
		$out .= "Referer: $boardurl\r\n";
		$out .= "Accept-Language: zh-cn\r\n";
		$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$out .= "Accept-Encoding: none\r\n";
		$out .= "User-Agent: Comsenz/1.0 ($version)\r\n";
		$out .= "Host: $host\r\n";
		$out .= 'Content-Length: ' . strlen ( $post ) . "\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Cache-Control: no-cache\r\n";
		$out .= "Cookie: $cookie\r\n\r\n";
		$out .= $post;
	} else {
		$out = "GET $script HTTP/1.1\r\n";
		$out .= "Accept: */*\r\n";
		$out .= "Referer: $boardurl\r\n";
		$out .= "Accept-Language: zh-cn\r\n";
		$out .= "Accept-Encoding:\r\n";
		$out .= "User-Agent: Comsenz/1.0 ($version)\r\n";
		$out .= "Host: $host\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Cookie: $cookie\r\n\r\n";
	}
	$fp = fsockopen ( $host, $port, $errno, $errstr, 30 );
	if (! $fp) {
		return "";
	} else {
		@fwrite ( $fp, $out );
		while ( ! feof ( $fp ) && $limit > - 1 ) {
			$limit -= 524;
			$return .= @fread ( $fp, 524 );
		}
		@fclose ( $fp );
		$return = preg_replace ( "/\r\n\r\n/", "\n\n", $return, 1 );
		$strpos = strpos ( $return, "\n\n" );
		$strpos = $strpos !== FALSE ? $strpos + 2 : 0;
		$return = substr ( $return, $strpos );
		return $return;
	}
}

?>